package com.daily.daily_push.controller;

import com.daily.daily_push.service.K8sApiService;
import com.daily.daily_push.utils.K8sApiClientUtil;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Namespace;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@Slf4j
public class K8sApiTest {
    @Resource
    K8sApiService k8sService;
    private ExecutorService executorService;

    @GetMapping("/test111")
    public Object  test111()  {
        ApiClient apiClient = K8sApiClientUtil.k8sConfigClient("aaaaa", "D:\\commonTest\\k8s\\config.yaml");
        List<V1Namespace> v1Namespaces = k8sService.listNamespace(apiClient);
        return v1Namespaces;
    }

    @GetMapping("/test222")
    public Object  test222()  {
        ApiClient apiClient = K8sApiClientUtil.k8sConfigClient("aaaaa", "D:\\commonTest\\k8s\\config.yaml");
        Map<String, Object> map = k8sService.k8sInfo(apiClient);
        return map;
    }

    @GetMapping("/app-test")
    public String  apptest(String cmd)  {
        executorService = Executors.newSingleThreadExecutor();
        String command = cmd;
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\s+"));
            Process process = processBuilder.start();

            // 异步处理命令输出
            executorService.execute(() -> processOutput(process));

            // 等待命令执行完成
            int exitCode = process.waitFor();
            System.out.println("命令执行完成，退出码：" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
       return "你好！ app-test";
    }


    private  void processOutput(Process process) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            StringBuilder output = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 将 output 存储到数据库
            saveToDatabase(output.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveToDatabase(String output) {
        // 将 output 存储到数据库的逻辑
        System.out.println("存储到数据库：" + output);
    }
}
